{-# LANGUAGE Rank2Types #-}
module Language.Dependencies.Main(

  module Language.Dependencies.GUI.Types
, module Language.Dependencies.References
, main'

) where

-- base
import System.Environment(getArgs)
import Data.IORef 
import Control.Monad ((=<<))

-- gtk
import Graphics.UI.Gtk hiding (get,Language) 

-- local
import Language.Dependencies.Language
import Language.Dependencies.References -- to parse a Rulefile at startup

-- local GUI
import Language.Dependencies.GUI.Actions 
  (actionEmptyGUI,actionLoadHeadless,setConfig) 
import Language.Dependencies.GUI.Types hiding (languages)
import Language.Dependencies.GUI.Build (buildAststate)

import System.Directory (getCurrentDirectory,getDirectoryContents)


-- --------------------------------------------------------
-- * main ()
-- --------------------------------------------------------


-- | loads LanguageRegistration, inits GTK-GUI, checks for a 
-- CLI-argument (one file to parse) and finally starts the GTK-GUI
main' :: Options -> [Language] -> IO ()
main' os ls = do 


  args <- getArgs
  
  files <- getDirectoryContents =<< getCurrentDirectory
  
  case args of

    ["-b"] -> do
      batch "Rulefile"

    ["-b",rulefile] -> do
      batch rulefile

    [] -> do
      ref <- buildAststate os ls
      if elem "Rulefile" files
        then do
          config <- 
            fmap readConfig $ readFile $ 
              head $ filter (=="Rulefile") files
          print config
          setConfig config ref
          actionEmptyGUI ref
        else actionEmptyGUI ref
      showUI ref

    [rulefile] -> do
      ref <- buildAststate os ls
      config <- fmap readConfig $ readFile rulefile
      print rulefile
      print config
      setConfig config ref
      actionEmptyGUI ref
      showUI ref

    [arg1,arg2] -> do
      ref <- buildAststate os ls
      actionLoadHeadless L arg1 ref 
      actionLoadHeadless R arg2 ref
      showUI ref

    _ -> 
      error "Zero, one or two parameter expected"
  
  where
    showUI :: (IORef AstState) -> IO ()
    showUI ref = do
       -- show UI
      gui <- getGui ref 
      widgetShowAll $ window gui 
      mainGUI
    
    
    batch :: FilePath -> IO ()
    batch rulefile = do
      contents <- readFile rulefile
      let references = (map readRelation) $ lines $ contents
     
      -- for all references, call "check"
      results <- mapM ck references
     
      -- print all results, zipped with their references 
      mapM_ print $ (zip references results)
    
    ck :: Relation -> IO Bool
    ck = check os  
